package com.laicunba.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.laicunba.pojo.RateIncrCouponDO;
import com.laicunba.pojo.RateIncrCouponDefDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.RateIncrCouponDefService;
import com.laicunba.service.RateIncrCouponService;
import com.laicunba.service.UserService;
import com.laicunba.util.AssertUtil;

@Service
public class RateIncrCouponDefServiceImpl extends BaseServiceImpl implements RateIncrCouponDefService {
	@Autowired
	private UserService userService;
	@Autowired
	private RateIncrCouponService rateIncrCouponService;

	@Transactional
	@Override
	public RateIncrCouponDO send2User(String defId, String uid, boolean justOne, String summary) {
		RateIncrCouponDefDO defDO = get(RateIncrCouponDefDO.class, defId);
		AssertUtil.assertNotNull(defDO, "DEF_NOT_EXIST");

		UserDO user = userService.get(UserDO.class, uid);
		AssertUtil.assertNotNull(user, "USER_NOT_EXIST");
		AssertUtil.assertTrue(!"disable".equalsIgnoreCase(user.getStatus()), "USER_DISABLED");

		AssertUtil.assertTrue(defDO.getTotalQuantity() >= defDO.getUsedQuantity(), "SEND_OUT");

		if (defDO.getBeginTime() != null && defDO.getEndTime() != null) {
			Date now = new Date();
			if (now.after(defDO.getEndTime())) {
				AssertUtil.assertFail("BEGIN_OR_ENDTIME_ERROR");
			}
		}
		RateIncrCouponDO rateIncrCouponDO = new RateIncrCouponDO();
		if (justOne) {
			rateIncrCouponDO.setId(defDO.getId() + "_" + user.getMobile());
		}

		rateIncrCouponDO.setRate(defDO.getRate());
		rateIncrCouponDO.setDefId(defDO.getId());
		rateIncrCouponDO.setConditions(defDO.getConditions());
		rateIncrCouponDO.setName(defDO.getName());
		rateIncrCouponDO.setStatus("new");
		rateIncrCouponDO.setUserId(user.getId());
		rateIncrCouponDO.setSummary(summary);
		if (defDO.getBeginTime() != null && defDO.getEndTime() != null) {
			rateIncrCouponDO.setBeginTime(defDO.getBeginTime());
			rateIncrCouponDO.setEndTime(defDO.getEndTime());
		}

		if (rateIncrCouponDO.getEndTime() == null && defDO.getValidDay() > 0) {
			Date now = new Date();
			now.setHours(0);
			now.setMinutes(0);
			now.setSeconds(0);

			rateIncrCouponDO.setBeginTime(new Date(now.getTime()));
			rateIncrCouponDO.setEndTime(new Date(now.getTime()));
			rateIncrCouponDO.getEndTime().setDate(rateIncrCouponDO.getEndTime().getDate() + defDO.getValidDay());
		}

		AssertUtil.assertTrue(rateIncrCouponService.create(rateIncrCouponDO), "RATE_INCR_COUPON_CREATE_FAIL");
		defDO.setUsedQuantity(defDO.getUsedQuantity() + 1);
		AssertUtil.assertTrue(this.updateSkipCheckOwner(defDO), "UPDATE_DEF_FAIL");
		return rateIncrCouponDO;
	}

}
